package org.nudt.system.controller

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import okhttp3.OkHttpClient
import okhttp3.Request
import org.nudt.common.model.Video
import org.nudt.common.model.fetch.RespData
import org.nudt.system.service.SysAdminService
import org.nudt.system.service.SysVideoService
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController


@RestController
@RequestMapping("/v1/system/fetch")
class SysFetchController(
    private val sysAdminService: SysAdminService,
    private val sysVideoService: SysVideoService,
    private val objectMapper: ObjectMapper,
    private val httpClient: OkHttpClient
) {
    private val logger = LoggerFactory.getLogger(SysFetchController::class.java)
    
    /**
     * 虎牙  https://www.huyaapi.com/api.php/provide/vod/at/json?ac=videolist&t=&pg=$page&h=&ids=&wd=
     * 暴风  https://bfzyapi.com/api.php/provide/vod/?ac=videolist&t=&pg=$page&h=&ids=&wd=
     * 光速  https://api.guangsuapi.com/api.php/provide/vod/?ac=videolist&t=&pg=1&h=&ids=&wd=
     */
    @GetMapping("/{startPage}/video")
    fun fetch(@PathVariable startPage: Int): String {
        var page = startPage
        var pageCount = 10000
        while (page <= pageCount) {
            val request: Request = Request.Builder()
                .url("https://api.guangsuapi.com/api.php/provide/vod/?ac=videolist&t=&pg=$page&h=&ids=&wd=")
                .build()
            
            try {
                val response = httpClient.newCall(request).execute()
                val resp: RespData<Video> = objectMapper.readValue(response.body.string())
                pageCount = resp.pagecount
                resp.list.forEach { video: Video ->
                    if (!sysVideoService.exists(video)) {
                        sysVideoService.download(false, video)
                    }
                    //  saveNotUpdate(video)
                }
                logger.info("fetch videos by page: $page")
            } catch (e: Exception) {
                e.printStackTrace()
            }
            page++
        }
        return "info"
    }
    
    @GetMapping("/pic")
    fun saveVideo(): String {
        val videoList = sysVideoService.findByVodPicStartingWith()
        videoList.forEach { video: Video ->
            sysVideoService.download(true, video)
        }
        return "success"
    }
    
    /**
     * 更新播放地址
     */
    @GetMapping("/url")
    fun updatePlayUrl() {
        sysVideoService.updateUrl()
    }
    
    @GetMapping("/serial")
    fun updateSerial() {
        sysVideoService.updateSerial()
    }
}